import Vue from 'vue'
import axios from 'axios'
import qs from 'qs'
import md5 from 'md5'

let loadTimeoutId;

let config = {
  issuer: '2G3JAjubBlYYxwos',
  secret: 'pxYSsnktmIyv6AiwEili7MGxC7r9JlBA',
};

function suijiStr() {
  return Math.random().toString(36).substr(2)
}

function signature(timeStrect, payload) {
  let params = [timeStrect, payload, config.secret];
  params.sort();
  return params.join('.')
}

axios.interceptors.request.use((conf) => {
  loadTimeoutId = setTimeout(() => {
    new Vue({}).$vux.loading.show({
      text: 'Loading'
    });
  }, 500);
  setTimeout(() => {
    new Vue({}).$vux.loading.hide();
  }, 600);
  let nowTime = new Date().getTime();
  let payload = suijiStr();
  conf.headers = {
    timestamp: nowTime,
    payload: payload,
    issuer: config.issuer,
    signature: md5(signature(nowTime, payload))
  };
  return conf
}, (error) => {
  //new Vue({}).$message.error('请求失败');
  return Promise.reject(error)
});
axios.interceptors.response.use((res) => {
  // console.log(res);
  clearTimeout(loadTimeoutId);
  new Vue({}).$vux.loading.hide();
  // console.log(res.data.code);
  if (res.status === 200) {
    return res.data;
  } else if (res.status === 209) {
    new Vue({}).$vux.alert.show({
      title: '提示',
      content: res.data.msg,
      onHide() {
        if (window.android) {
          window.android.backGuessCenter();
        } else {
          window.webkit.messageHandlers.lwdkit.postMessage({
            action: "gameEndShouldPop",
            data: {}
          })
          //gameEndShouldPop
        }
        // console.log('Plugin: I\'m hiding now')
      }
    })
  }

  // if (res.data.code === 0) {
  //   return res.data;
  //   // new Vue({}).$vux.toast.show({type: 'warn', text: '请求错误'});
  //   // new Vue({}).$vux.toast.show({type:'text', text:`${res.data.msg}`, width:`50%`, time:2500});
  // } else if (res.data.code === 1) {
  //   return res.data
  // } else if (res.data.code === 2) {
  //
  // } else if (res.data.code === 3) {
  //
  // } else if (res.data.code === 4) {
  //
  // } else if (res.status === 200) {
  //   return res.data;
  // } else {
  //
  // }
  // return Promise.reject(res);
}, (error) => {
  // console.log(error)
  new Vue({}).$vux.loading.hide();
  clearTimeout(loadTimeoutId);
  if (error.response.status == 421) {
    if (error.response.data.msg == '该手机号已经注册') {
      // new Vue({}).$vux.toast.text(error.response.data.msg);
      new Vue({}).$vux.confirm.show({
        title: '您已注册过',
        content: '现在去邀请好友？',
        onCancel() {
          console.log('prompt cancel')
        },
        onConfirm(msg) {
          window.location.href = window.location.origin + '/my/getvip.html'
        }
      })
    } else {
      new Vue({}).$vux.toast.text(error.response.data.msg)
      return Promise.reject(error)
    }
  } else {
    new Vue({}).$vux.toast.show({type: 'warn', text: '响应失败'});
    return Promise.reject(error)
  }
});

const ajax = {
  get: (url, params) => {
    return axiosRequestParams(url, 'get', params, 10000);
  },
  post: (url, params) => {
    return axiosRequestParams(url, 'post', params, 15000);
  },
  put: (url, params) => {
    return axiosRequestParams(url, 'put', params, 10000);
  },
  uploadForm: (url, params, formData) => {
    // 处理提交评论的个自定义方法
    return axiosRequestParams(url, 'post', params, 0, formData);
  }
};

function axiosRequestParams(url, method, paramsOrData, timeout, formData) {
  let params = {};
  let data = {};
  paramsOrData = paramsOrData || {};
  // window.localStorage.setItem('jcyy_uid',res.data.id);
  // window.localStorage.setItem('jcyy_token',res.data.token)
  // paramsOrData.token = window.localStorage.getItem('jcyy_token') ? window.localStorage.getItem('jcyy_token') : '';
  // paramsOrData.uid = window.localStorage.getItem('jcyy_uid') ? window.localStorage.getItem('jcyy_uid') : '';
  if (method === 'get' || method === 'delete' || method === 'head') {
    params = paramsOrData;
    data = {};
  } else {
    params = {};
    data = qs.stringify(paramsOrData);
  }
  // 有formData 走这个；
  if (formData != null) {
    for (let attr in paramsOrData) {
      formData.append(attr, paramsOrData[attr]);
    }
  }
  return axiosRequest({
    method: method,
    url: url,
    params: params,
    data: formData ? formData : data,
    timeout: 10000
  })
}

function axiosRequest(conf) {
  return axios({
    method: conf.method || 'get',
    url: conf.url,
    params: conf.params || {},
    data: conf.data,
    timeout: conf.timeout || 10000
  })
}

Vue.prototype.$ajax = ajax;

